package socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**\
 * 基于UDP的socket
 * Created by zzy on 2018/1/9.
 */
public class UDPServer {



    public static void main(String[] args) throws IOException {
        /*
        接收
         */
        //1、创建服务器端DataGramSocket,指定端口
        DatagramSocket socket=new DatagramSocket(9999);
        //创建数据包
        byte[] data=new byte[1024];
        DatagramPacket packet=new DatagramPacket(data,data.length);
        //3、接收客户端发送的数据
        socket.receive(packet);//阻塞
        //4、读取数据
        String info=new String(data,0,packet.getLength());
        Print.print("我是服务器:"+info);

        /**
         * 响应
         */
        InetAddress address=packet.getAddress();
        int port=packet.getPort();
        byte[] returndata="欢迎您".getBytes();
        //2、创建数据报
        DatagramPacket packet1=new DatagramPacket(returndata,returndata.length,address,port);
        socket.send(packet1);
        //3、关闭
        socket.close();
    }
}
